import styles from './index.less';
import { useState, useEffect } from 'react';
import { useIntl } from 'umi';
import { Space, Button, Input, Upload, message, Popconfirm } from 'antd';
import {
  SearchOutlined,
  UploadOutlined,
  CloseOutlined,
} from '@ant-design/icons';
import ShortcutOptions from '@/pages/components/shortcutOptions';
import imgAttach from '@/images/reply/attach.svg';

const { Dragger } = Upload;
const { TextArea } = Input;

import request from '@/utils/request';
import { getToken } from '@/utils/auth';
import config from '@/config';
function QuickrepliesPage() {
  const intl = useIntl();

  const [qrlist, setQrlist] = useState([]);

  const [keyword, setKeyword] = useState('');

  const defaultFormData = {
    id: '',
    title: '',
    content: '',
    attachment: [],
  };

  const [formData, setFormData] = useState(defaultFormData);

  const [fileList, setFileList] = useState([]);

  useEffect(() => {
    getAutoReply();
  }, []);

  // const onCreate = () => {

  // }

  const getAutoReply = () => {
    request.get('/autoReply/get').then((res) => {
      setQrlist(res.data.autoReplyList);
    });
  };

  const submitAutoReply = () => {
    const data = { ...formData };
    let url = '/autoReply/create';
    let type = 'post';
    if (data.id) {
      url = '/autoReply/edit';
      type = 'patch';
    }
    data.attachment = fileList;
    request[type](url, data).then((res) => {
      getAutoReply();
      setFormData({
        ...res.data.autoReply,
        attachmentList: res.data.attachmentList,
      });

      setFileList(
        data.id
          ? res.data.autoReply.attachmentList
          : res.data.attachmentList || [],
      );

      message.success(
        intl.formatMessage({ id: data.id ? 'updatesuccess' : 'createsuccess' }),
      );
    });
  };

  const onSelectedItem = (item: any) => {
    setFormData(item);
    setFileList(item.attachmentList);
  };

  // 选择快捷回复
  const onSelectShortcut = (type: string) => {
    setFormData({
      ...formData,
      content: `${formData.content}{{${type}}}`,
    });
  };

  const uploadProps = {
    name: 'file',
    accept: 'image/*',
    multiple: true,
    action: config.baseURL + '/system/fileUpload',
    showUploadList: false,
    // fileList,
    headers: {
      'Access-Token': getToken(),
    },
    beforeUpload(file: any) {
      const isImg = file.type.indexOf('image/') >= 0;
      if (!isImg) {
        message.error(intl.formatMessage({ id: 'p_s_imgtype' }));
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      // if (!isLt5M) {
      //   message.error('Image must smaller than 2MB!');
      // }
      return isImg;
    },
    onChange(info: any) {
      console.log(info);
      const { file, fileList } = info;
      if (file.status !== 'uploading') {
        console.log(file, fileList);
      }
      if (file.status === 'done') {
        const { data } = file.response;
        const fileInfo = {
          url: data.url,
          fileName: data.fileName,
          type: data.type,
        };
        setFileList([fileInfo]);
      } else if (file.status === 'error') {
        message.error(`${file.name} file upload failed.`);
      }
    },
  };

  const onRemoveFile = (i: number) => {
    setFileList([]);
  };

  const onCancel = () => {
    setFormData(defaultFormData);
    setFileList([]);
  };

  const onChangeKeyword = (e: any) => {
    const { value } = e.target;
    setKeyword(value);
  };

  const onRemove = () => {
    request.delete(`/autoReply/${formData.id}`).then((res) => {
      getAutoReply();
      setFormData(defaultFormData);
      setFileList([]);
    });
  };

  return (
    <div className={styles.quickrepliesPage}>
      <div className={styles.head}>
        <h4 className={styles.title}>
          {intl.formatMessage({ id: 'autoreplies' })}
        </h4>
        {/* <Space>
          <Button type="primary" onClick={createAutoReply}>{intl.formatMessage({ id: 'create' })}</Button>
        </Space> */}
      </div>
      <div className={styles.content}>
        <div className={styles.search}>
          <Input
            value={keyword}
            className={styles.searchInput}
            size="large"
            placeholder={intl.formatMessage({ id: 'search' })}
            prefix={<SearchOutlined />}
            onChange={onChangeKeyword}
          />
        </div>
        <div className={styles.main}>
          <div className={styles.left}>
            <div className={`${styles.quickreolieList} noscrollbar`}>
              {qrlist.map((n) =>
                !keyword || (n.title + n.content).indexOf(keyword) >= 0 ? (
                  <div
                    key={n.id}
                    className={`${styles.listItem} ${
                      formData.id === n.id ? styles.selected : ''
                    }`}
                    onClick={() => onSelectedItem(n)}
                  >
                    <span>{n.title}</span>
                    {n.attachmentList && n.attachmentList.length ? (
                      <img src={imgAttach} className={styles.itemicon} alt="" />
                    ) : null}
                  </div>
                ) : (
                  ''
                ),
              )}
            </div>
          </div>

          <div className={styles.mainContent}>
            <div className={styles.title}>
              <Input
                value={formData.title}
                placeholder={intl.formatMessage({ id: 'p_i_title' })}
                size="large"
                onChange={(e) =>
                  setFormData({ ...formData, title: e.target.value })
                }
              />
            </div>
            <div className={styles.form}>
              <div className={styles.formContent}>
                {fileList.length ? (
                  <div className={styles.fileList}>
                    {fileList.map((n, i) => (
                      <div key={i} className={styles.fileItem}>
                        <img className={styles.img} src={n.url} alt="" />
                        <CloseOutlined
                          className={styles.closeicon}
                          onClick={() => onRemoveFile(i)}
                        />
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className={styles.uploadCon}>
                    <Dragger {...uploadProps}>
                      <div className={styles.uploadDragCon}>
                        <UploadOutlined />
                        <p>{intl.formatMessage({ id: 'uploadtext_img' })}</p>
                      </div>
                    </Dragger>
                  </div>
                )}
                <div className={styles.textarea}>
                  <TextArea
                    value={formData.content}
                    style={{ height: '100%' }}
                    placeholder={intl.formatMessage({ id: 'p_e_atemplate' })}
                    onChange={(e) =>
                      setFormData({ ...formData, content: e.target.value })
                    }
                  ></TextArea>
                </div>
              </div>
              <ShortcutOptions onSelect={onSelectShortcut} />
            </div>
          </div>
        </div>
        <div className={styles.btns}>
          <Space>
            <Button onClick={onCancel}>
              {intl.formatMessage({ id: 'cancel' })}
            </Button>
            <Button type="primary" onClick={submitAutoReply}>
              {intl.formatMessage({ id: formData.id ? 'update' : 'create' })}
            </Button>

            {formData.id ? (
              <Popconfirm
                placement="topRight"
                title={intl.formatMessage({ id: 'RU_delete' })}
                onConfirm={onRemove}
                okText={intl.formatMessage({ id: 'yes' })}
                cancelText={intl.formatMessage({ id: 'no' })}
              >
                <Button type="danger">
                  {intl.formatMessage({ id: 'remove' })}
                </Button>
              </Popconfirm>
            ) : null}
          </Space>
        </div>
      </div>
    </div>
  );
}

QuickrepliesPage.title = '管理快速回复';

export default QuickrepliesPage;
